package com.itcam.thread_.lock;

public class ThreadTest5 {
    /*
        静态同步方法
     */
    public static void main(String[] args) {
        TicketTask5 task = new TicketTask5();

        Thread t1 = new Thread(task, "窗口1");
        Thread t2 = new Thread(task, "窗口2");

        t1.start();
        t2.start();
    }
}

class TicketTask5 implements Runnable {

    private static int tickets = 100;

    @Override
    public void run() {
        while (true) {

            String name = Thread.currentThread().getName();

            if ("窗口1".equals(name)) {
                if (method()) {
                    break;
                }
            } else if ("窗口2".equals(name)) {
                synchronized (TicketTask5.class) {
                    if (tickets == 0) {
                        break;
                    }
                    System.out.println(Thread.currentThread().getName() + "卖出了第" + tickets + "号票");
                    tickets--;
                }
            }


        }
    }

    private static synchronized boolean method() {
        if (tickets == 0) {
            return true;
        }

        System.out.println(Thread.currentThread().getName() + "卖出了第" + tickets + "号票");
        tickets--;
        return false;
    }
}
